//
//  LoginVC.m
//  ProjectforHDX
//
//  Created by Jaesun on 16/6/30.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "LoginVC.h"

#import "mainVC.h" // 主页
#import "ChangeURLVC.h" // 更换URL

@interface LoginVC () {
    /**
     *  用户模型信息
     */
    THUserInfoModel *userModel;
    
    /**
     *  用户账号密码信息
     */
    NSMutableDictionary *userDict;
}

/**
 *  系统标志图片
 */
@property (nonatomic, strong) UIImageView *iconImageView;
/**
 *  用户名输入视图
 */
@property (nonatomic, strong) LoginInputView *accountInputView;
/**
 *  密码输入视图
 */
@property (nonatomic, strong) LoginInputView *passwordInputView;
/**
 *  登录按钮
 */
@property (strong, nonatomic) UIButton *loginBtn;

/**
 *  最下面的提示
 */
@property (nonatomic, strong) UILabel *promptLabel;

/**
 *  版权信息标签
 */
@property (nonatomic, strong) UILabel *rightCopyLabel;
/**
 *  更换URL按钮
 */
@property (strong, nonatomic) RZCustomButtom *changeURLBtn;


/**
 *  用户输入的账号
 */
@property (copy, nonatomic) NSString *account;
/**
 *  用户输入的密码
 */
@property (copy, nonatomic) NSString *password;

@end

@implementation LoginVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
 
}
- (void)viewDidLoad {

    [super viewDidLoad];
  
    //变量初始化
    [self varInit];
    
    //UI初始化
    [self UIConfig];
  

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 变量、UI初始化
/**
 *  变量初始化
 */
- (void)varInit{
    userModel = [[THUserInfoModel alloc]init];
    userDict = [[NSMutableDictionary alloc]init];
    
    [self getAccountAndPassword];
}

/**
 *  界面UI初始化
 */
- (void)UIConfig{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // navgationController
    self.navigationController.navigationBar.hidden = YES; // 隐藏导航栏
    self.navColor=[UIColor whiteColor]; //隐藏导航栏线条
    self.labnav.backgroundColor = [UIColor clearColor];
    self.leftItem.hidden=YES; //隐藏导航栏左边的按钮
    
    // iconImageView
    UIImage *logoimg=BDFILEIMAGENAEM(@"Login/img_logo");
    self.iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.width - logoimg.size.width)/2, (SCREEN_HEIGHT / 8) + 20, logoimg.size.width, logoimg.size.height)];
    self.iconImageView.backgroundColor = [UIColor clearColor];
    self.iconImageView.image=logoimg;
    [self.view addSubview:self.iconImageView];
    
    // accountInputView
    self.accountInputView = [[LoginInputView alloc] initWithFrame:CGRectMake(50, CGRectGetMidY(self.view.frame) - 50, SCREEN_WIDTH - 50 * 2, 50)];
    self.accountInputView.iconImg=BDFILEIMAGENAEM(@"Login/img_userName");
    self.accountInputView.textField.placeholder = [UtilCheck language:@"login.name"]; // 请输入手机号
    self.accountInputView.textField.keyboardType=UIKeyboardTypeDefault;
    [self.accountInputView.textField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:self.accountInputView];
    
    // passwordInputView
    self.passwordInputView = [[LoginInputView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.accountInputView.frame),CGRectGetMaxY(self.accountInputView.frame) + 5, CGRectGetWidth(self.accountInputView.frame), CGRectGetHeight(self.accountInputView.frame))];
    self.passwordInputView.textField.placeholder = [UtilCheck language:@"login.password"]; // 请输入密码
    [self.passwordInputView.textField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.passwordInputView.textField.keyboardType=UIKeyboardTypeASCIICapable;
    self.passwordInputView.textField.secureTextEntry=YES;
    self.passwordInputView.iconImg=BDFILEIMAGENAEM(@"Login/img_password");
    [self.view addSubview:self.passwordInputView];
    
    // loginBtn
    self.loginBtn = [[RZCustomButtom alloc] init];
    self.loginBtn.frame = CGRectMake(CGRectGetMinX(self.accountInputView.frame), CGRectGetMaxY(self.passwordInputView.frame) + 35, CGRectGetWidth(self.accountInputView.frame), 40);
    [self.loginBtn setBackgroundImage:BDFILEIMAGENAEM(@"Login/btn_login") forState:(UIControlStateNormal)];
    [self.loginBtn setBackgroundImage:BDFILEIMAGENAEM(@"Login/btn_login_highlight") forState:(UIControlStateHighlighted)];
    [self.loginBtn setTitle:[UtilCheck language:@"login.login"] forState:(UIControlStateNormal)]; // 登录
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.loginBtn setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn addTarget:self action:@selector(touchLoginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.promptLabel = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height - 35, 250, 30)];
    self.promptLabel.text = @"专业SPM服务提供商";
    self.promptLabel.textAlignment = NSTextAlignmentCenter;
    self.promptLabel.font = [UIFont systemFontOfSize:11];
    self.promptLabel.textColor = [UtilCheck hexStringToColor:@"a8a8a8" alpha:1];
    [self.view addSubview:self.promptLabel];
    
    // 如果本地保存了用户名和密码，初始化到视图上
    if (self.account.length != 0) {
        self.accountInputView.textField.text = self.account;
    
    }
    
//#ifdef DEBUG
    //服务器切换
#pragma mark appStore Test Account
    if (![Toolobject isAppStoreTestAccount]) {
        self.changeURLBtn=[[RZCustomButtom alloc] init];
        UIImage *btnimg=BDFILEIMAGENAEM(@"Login/btn_server");
        [ self.changeURLBtn setFrame:CGRectMake(self.view.width - btnimg.size.width, self.view.bottom-btnimg.size.height, btnimg.size.width, btnimg.size.height)  ];
        [self.changeURLBtn setImage:btnimg forState:UIControlStateNormal];
        [self.changeURLBtn addTarget:self action:@selector(touchChangeURLBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.changeURLBtn];
    }
//#endif
    
}

#pragma mark 获取本地存储的账号密码
/**
 *  读取本地存储的账号密码
 */
- (void)getAccountAndPassword{
    userDict = [NSMutableDictionary dictionaryWithDictionary:[THMangerTool getKeepAccout]];
    if (0 < [userDict allKeys].count) {
        self.account = [userDict objectForKey:@"username"];
        self.password = [userDict objectForKey:@"password"];
    }
    else{
        userDict=[[NSMutableDictionary alloc] initWithCapacity:0];
    }
}


#pragma mark 点击登录按钮
- (void)touchLoginBtn:(id)sender {
    
    [self.view endEditing:YES];
    
    self.account = self.accountInputView.textField.text;
    self.password = self.passwordInputView.textField.text;
    
    if (self.account.length == 0 || self.password.length == 0) {
        [Toolobject showAlterwithMessage:[UtilCheck language:@"login.empty"] inVC:self]; // @"请输入手机号和密码"
        return;
    }
   
    self.account = [UtilCheck clearSpace:self.account isends:NO];
    // Post参数
    [userDict setValue:self.account forKey:@"username"];
    [userDict setValue:self.password forKey:@"password"];
    [self loginWithUserDic:userDict];
    
}

#pragma mark 更换服务器地址
- (void)touchChangeURLBtn:(RZCustomButtom *)sender {
    
   ChangeURLVC * vc = [[ChangeURLVC alloc] init];
   [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark 登录数据请求
- (void)loginWithUserDic:(NSMutableDictionary *)dic {
    {
        [[BDHUD sharedManager] showBDHUD:self.view title:nil];
        [AFHttpTool postJsonDatawithUrl:@"applogin1_2" parameters:[dic mutableCopy] success:^(id responseObject) {
//            [AFHttpTool postJsonDatawithUrl:@"applogin"parameters:[dic mutableCopy] success:^(id responseObject) {

            [[BDHUD sharedManager] dismissHUD];
            if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
                
                // 登录服务器成功后 保存用户名和密码到本地
                [THMangerTool saveAccountInfo:dic];
                
                if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                    
                    NSDictionary *dic = [[responseObject objectForKey:@"data"] objectForKey:@"user"];

                    NSLog(@"store========%@",dic);
                    
                    userModel = [UtilCheck dictionarytoModel:dic targetModel:@"THUserInfoModel"]; // 把字典转化为model
                    userModel.imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"headImage"]]];
                    [THMangerTool saveAccountModel:userModel];
                    
                    if(self.isdismiss){
                        [self leftItem:nil];
                        //创建通知
                        NSNotification *notification =[NSNotification notificationWithName:@"loginStatus" object:nil userInfo:nil];
                        //通过通知中心发送通知
                        [[NSNotificationCenter defaultCenter] postNotification:notification];
                    }
                    else{
 
                        [APPDELEGATESelf setUpMainViewControllerOrLoginViewController:YES];
                    }
                }
            }
            else {
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else {
                     [[BDHUD sharedManager] showWords:[UtilCheck language:@"login.failed"]]; // 登录错误！ code： 2005
                }
            }
            
        } fail:^(id responseObject, NSError *error) {
            
            [[BDHUD sharedManager] dismissHUD];
            
            if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
            }else {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
            }
           
        }];
    }
}

@end
